package com.eras.shoes.utils

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.tasks.CancellationTokenSource
import kotlinx.coroutines.tasks.await

class LocationProvider(private val context: Context) {
    private val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)

    @SuppressLint("MissingPermission")
    suspend fun getCurrentLocation(): LocationResult {
        return try {
            if (!context.hasLocationPermission()) {
                return LocationResult.Error("Location permission denied")
            }

            val location = fusedLocationClient.getCurrentLocation(
                Priority.PRIORITY_HIGH_ACCURACY,
                CancellationTokenSource().token
            ).await()

            location?.let {
                LocationResult.Success(it.latitude, it.longitude)
            } ?: LocationResult.Error("Location unavailable")
        } catch (e: Exception) {
            LocationResult.Error(e.localizedMessage ?: "Unknown error")
        }
    }

    sealed class LocationResult {
        data class Success(val latitude: Double, val longitude: Double) : LocationResult()
        data class Error(val message: String) : LocationResult()
    }
}

fun Context.hasLocationPermission(): Boolean {
    return ContextCompat.checkSelfPermission(
        this,
        Manifest.permission.ACCESS_FINE_LOCATION
    ) == PackageManager.PERMISSION_GRANTED
}
